﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Automation;
using System.Windows.Forms;

namespace YTSK.cSK.HT
{
    public class cKP_PP
    {

        [System.Runtime.InteropServices.ComVisibleAttribute(true)]
        public static string proc(string filepath, out string fpdm,out string fphm)
        {
            var sk_delay = cSK.cSKSet.loadsave(SkConfig.延时设置).ObjToInt();
            if (sk_delay == 0) { sk_delay = 500; }
            var err = "";
            fpdm = "";fphm = "";
            var sname = new StringBuilder();
            #region 获取主窗口
            sname.Append("开具增值税普通发票");
            var mainwin = new Model.WinProperty();
            mainwin.hwnd = cDll.FindWindow(null, sname);
            if (mainwin.hwnd.ToInt32() == 0)
            { err = "没有找到开票系统的窗口，请先打开"; return err; }
            cDllExt.GetWinProperty(mainwin);
            cDll.SwitchToThisWindow(mainwin.hwnd, true);
            var childrens = cDllExt.GetAllChild(mainwin.hwnd);
            #endregion


            #region 获取发票号码
            err = GetVouchCode(childrens, out fpdm, out fphm);
            if (err.Length>0) { return err; }            
            #endregion

            #region 点击导入按钮
            var input = childrens.FirstOrDefault(s => Math.Abs(s.position.Top - mainwin.position.Top - 30) <= 10
                 & s.position.Height - s.position.Top == 50 & s.position.Width > 600);
            if (input == null) { err = "没有找到导入按钮"; return err; }
            var x = input.position.Width - 673;
            var y = input.position.Top + 25;
            //cDll.SetForegroundWindow(mainwin.hwnd);
            #endregion

            int ifindount = 0;
            #region 点击手工导入
            Step1:
            cDllExt.mouseClick(x, y);
            System.Threading.Thread.Sleep(sk_delay + ifindount*100);
            cDllExt.mouseClick(x+20, y+60);
            #endregion

            #region 选择导入文件
            System.Threading.Thread.Sleep(sk_delay + ifindount*100);
            var openwin = new Model.WinProperty();
            sname = new StringBuilder();
            sname.Append("打开");
            //openwin.hwnd = cDll.FindWindowEx(mainwin.hwnd, IntPtr.Zero, null, openname);
            openwin.hwnd = cDll.FindWindow(null, sname);
            //while (openwin.hwnd.ToInt32() == 0 && ifindount < 500)
            //{
            //    //openwin.hwnd = cDll.FindWindowEx(mainwin.hwnd, IntPtr.Zero, null, openname);
            //    openwin.hwnd = cDll.FindWindow(null, sname);
            //    if (openwin.hwnd.ToInt32() == 0)
            //    { System.Threading.Thread.Sleep(200); }
            //    ifindount++;
            //}
            if (openwin.hwnd.ToInt32() == 0 && ifindount <5)
            {
                //System.Threading.Thread.Sleep(200);
                ifindount++;
                goto Step1;
            }

            if (openwin.hwnd.ToInt32() == 0 )
            {
                err+=$"没有找到窗口[{sname}]或者系统运行速度太慢，请与系统管理员联系";
                return err;
            }

            cDllExt.GetWinProperty(openwin);
            var openmainOle = AutomationElement.FromHandle(openwin.hwnd);
            var condition0 = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit);
            var condition1 = new PropertyCondition(AutomationElement.NameProperty, "文件名(N):");
            var andcondition = new AndCondition(condition0, condition1);
            var eliemt = openmainOle.FindFirst(TreeScope.Descendants, andcondition);
            ifindount = 0;
            while (eliemt == null && ifindount < 5)
            {
                eliemt = openmainOle.FindFirst(TreeScope.Descendants, andcondition);
                ifindount++;
                if (eliemt == null) { System.Threading.Thread.Sleep(sk_delay); }
            }
            var vt = (ValuePattern)eliemt.GetCurrentPattern(ValuePattern.Pattern);
            vt.SetValue(filepath);
            condition0 = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button);
            condition1 = new PropertyCondition(AutomationElement.NameProperty, "打开(O)");
            eliemt = openmainOle.FindFirst(TreeScope.Children, andcondition);
            if (eliemt == null)
            { eliemt = openmainOle.FindFirst(TreeScope.Children, condition1); }

            if (eliemt == null)
            {
                var itop = openwin.position.Height - 50 + 25;
                var ileft = openwin.position.Width - 213 + 40;
                cDll.SetCursorPos(ileft, itop);
                cDllExt.mouseDoubleClick(ileft, itop);
            }
            else
            {
                var rect = eliemt.Current.BoundingRectangle;
                var itop = (int)(rect.Top + rect.Height / 2);
                var ileft = (int)(rect.Left + rect.Width / 2);
                cDll.SetCursorPos(ileft, itop);
                cDllExt.mouseDoubleClick(ileft, itop);
                //var clickpattern = (InvokePattern)eliemt.GetCurrentPattern(InvokePattern.Pattern);
                //clickpattern.Invoke();
            }

            //MessageBox.Show(openwin.text.ToString());
            #endregion
            System.Threading.Thread.Sleep(sk_delay);
            #region 导入单据选择窗体
            sname = new StringBuilder();
            sname.Append("导入单据信息查询选择");
            var importwin = new Model.WinProperty();
            ifindount = 0;
            while (importwin.hwnd.ToInt32() == 0 && ifindount < 5)
            {
                importwin.hwnd = cDll.FindWindow(null, sname);
                if (importwin.hwnd.ToInt32() == 0) { System.Threading.Thread.Sleep(sk_delay); }
                ifindount++;
            }
            if (importwin.hwnd.ToInt32() == 0)
            { err = "没有找到[导入单据信息查询选择]窗口"; return err; }
            cDllExt.GetWinProperty(importwin);
            var children_dr = cDllExt.GetAllChild(importwin.hwnd);
            var toolstrip = children_dr.FirstOrDefault(s => s.text == "toolStrip1");
            if (toolstrip == null) { err = "没有找到导入窗口的工具栏窗口";return err; }
            x = toolstrip.position.Width - 85;
            y = toolstrip.position.Top + 25;
            cDllExt.mouseClick(x, y);
            return err;
            #endregion
        }

        private List<Model.SKFP> GetMoney(Model.WinProperty main, int irows)
        {
            var l = new List<Model.SKFP>();
            var lw = cDllExt.GetAllChild(main.hwnd);
            var grid = lw.FirstOrDefault(s => s.position.Left == main.position.Left + 11
              & s.position.Top == main.position.Top + 244);
            if (grid == null) { return l; }
            for (int i = 0; i < irows; i++)
            {
                var skfp = new Model.SKFP();
                var top = grid.position.Top + i * 16 + 19 + 5;

                #region 存货名称--左边长度14
                var left = grid.position.Left + 14 + 15;
                string stext;
                var bret = GetGridData(grid, ref left, top, out stext);
                if (!bret) { return l; }
                skfp.invname = stext;
                #endregion

                #region 规格型号
                bret = GetGridData(grid, ref left, top, out stext);
                if (!bret) { return l; }
                skfp.invstd = stext;
                #endregion

                #region 单位
                bret = GetGridData(grid, ref left, top, out stext);
                if (!bret) { return l; }
                skfp.dw = stext;
                #endregion

                #region 数量
                bret = GetGridData(grid, ref left, top, out stext);
                if (!bret) { return l; }
                skfp.quantity = decimal.Parse(stext);
                #endregion

                #region 单价
                bret = GetGridData(grid, ref left, top, out stext);
                if (!bret) { return l; }
                skfp.unitprice = decimal.Parse(stext);
                #endregion

                #region 金额
                bret = GetGridData(grid, ref left, top, out stext);
                if (!bret) { return l; }
                skfp.totalprice = decimal.Parse(stext);
                #endregion

                #region 税率
                bret = GetGridData(grid, ref left, top, out stext);
                if (!bret) { return l; }
                skfp.taxrate = decimal.Parse(stext);
                #endregion

                #region 税额
                bret = GetGridData(grid, ref left, top, out stext);
                if (!bret) { return l; }
                skfp.tax = decimal.Parse(stext);
                #endregion
                l.Add(skfp);
            }

            //var grid = AutomationElement.FromHandle(gridori.hwnd);


            return l;
        }

        private bool GetGridData(Model.WinProperty grid, ref int x, int y, out string text)
        {
            cDllExt.mouseDoubleClick(x, y);
            var lw = cDllExt.GetAllChild(grid.hwnd);
            cDll.keybd_event((byte)Keys.Escape, 0, 0, 0);
            cDll.keybd_event((byte)Keys.Escape, 0, 2, 0);
            if (lw.Count > 0)
            {
                var a = lw[0];
                x = a.position.Width + 10;
                text = a.text; return true;
            }
            else { text = ""; return false; }
        }

        private static string GetVouchCode(List<Model.WinProperty> childrens, out string fpdm, out string fphm)
        {
            var err = ""; fpdm = ""; fphm = "";
            var maininput = childrens.FirstOrDefault(s =>Math.Abs( s.position.Width-s.position.Left- 945)<=5
              & Math.Abs( s.position.Height-s.position.Top- 629)<=5);
            if (maininput == null) { err = "没有找到发票数据"; return err; }
            var tmp = childrens.FirstOrDefault(s =>Math.Abs( s.position.Left - maininput.position.Left- 140)<=5
            &Math.Abs( s.position.Top -maininput.position.Top - 40)<=5);
            if(tmp!=null)
            { fpdm = tmp.text; }
            else { err = "没有找到发票代码"; return err; }
            tmp = childrens.FirstOrDefault(s => Math.Abs(s.position.Left- maininput.position.Left- 672)<=5
              &Math.Abs( s.position.Top - maininput.position.Top - 40)<=5);
            if (tmp!=null)
            { fphm = tmp.text; }
            else { err = "没有找到发票号码"; return err; }
            return err;
        }




    }
}
